%% Parameter
% measDir = ['..' filesep '210518_Faruq_1Wildbat'];
% 
% flagGate = 1;
% 
% rSqrCutoff = 0.6;
% areaGateRange = [10 30];
% velocityGateRange = [2 5]; % cm/s
% tau1GateRange = [0 11.4]; % ms
% tau2GateRange = [0 11.4]; % ms
% deltaDefoRange = [0 .5];

%% preamble
FTDir = [measDir filesep 'FTFitData' filesep];
idx = find(measDir == filesep);
exportName = [FTDir  measDir(idx(end)+1:end)];
% log file
diary([exportName '.log']);
fprintf('\n');
disp(datetime('now','TimeZone','Europe/Zurich','Format','d-MMM-y HH:mm:ss Z'));
fprintf('%s = %s\n','measDir',measDir);
fprintf('%s = %s\n','FTDir',FTDir);
fprintf('%s = %g\n','rSqrCutoff',rSqrCutoff);
fprintf('%s = [%g %g] um^2\n','areaGateRange',areaGateRange);
fprintf('%s = [%g %g] cm/s\n','velocityGateRange',velocityGateRange);
fprintf('%s = [%g %g] ms\n','tau1Range',tau1GateRange);
fprintf('%s = [%g %g] ms\n','tau2Range',tau2GateRange);
fprintf('%s = [%g %g]\n','deltaDefoRange',deltaDefoRange);

%% find samples and choose
dirRes = dir(FTDir);
dirRes = dirRes([dirRes.isdir]);
samples = cell(1,length(dirRes)-2);
flowRates = cell(1,length(dirRes)-2);
fprintf('Index\tName\t\t\tFlowRate\n');
mask = true(1,length(dirRes)-2);
for k = 3:length(dirRes)
    idxUnder = find(dirRes(k).name == '_');
    if length(idxUnder) >= 2
        samples{k-2} = dirRes(k).name(1:idxUnder(end-1)-1);
        flowRates{k-2} = dirRes(k).name(idxUnder(end-1)+1:idxUnder(end)-1);
        fprintf('%d\t%s\t\t%s\n',k-2,samples{k-2},flowRates{k-2});
    else
        mask(k-2) = false;
    end
end
samples = samples(mask); flowRates = flowRates(mask);
% idxSample = input('Choose samples: ');
% if not(isempty(idxSample))
%     samples = samples(idxSample);
%     flowRates = flowRates(idxSample);
% end

%% create results table
TComplete = table;
fprintf([repmat('-',1,length(samples)) '\n']);
for idxSample = 1:length(samples)
    dirRes = dir([FTDir samples{idxSample} '_' flowRates{idxSample} '_*' ]);
    dataMatDir = [dirRes.folder filesep dirRes.name];
    load([dataMatDir filesep 'data.mat']);
    
    %% area & velocity vectors
    areaVec = zeros(size(cellNums));
    veloVec = zeros(size(cellNums));
    ptr = 1;
    for k = 1:length(sampleData)
        tmp = [sampleData(k).measData.cellData.data];
        if ~isempty(tmp)
            areaVec(ptr:ptr+length(tmp)-1) = [tmp.medianArea];
            veloVec(ptr:ptr+length(tmp)-1) = [tmp.medianVelocity];
            ptr = ptr + length(tmp);
        end
    end
    
    %% deltaDefo
    deltaDefoTau1 = defoTau1Inlet - defoTau1Outlet;
    deltaDefoTau2 = defoTau2Outlet - defoTau2Inlet;
    
    %% gates
    maskTau1Consistency = (taus1Circularity >= 0) & (rSqrsCircularityTau1 >= rSqrCutoff) & (imag(taus1Circularity) == 0);
    maskTau2Consistency = (taus2Circularity >= 0) & (rSqrsCircularityTau2 >= rSqrCutoff) & (imag(taus2Circularity) == 0);

    if flagGate
        maskArea = (areaGateRange(1) <= areaVec) & (areaVec <= areaGateRange(2));
        maskVelo = (velocityGateRange(1) <= veloVec) & (veloVec <= velocityGateRange(2));
        maskCell = maskArea & maskVelo;

        maskTau1Range = (tau1GateRange(1) <= taus1Circularity) & (taus1Circularity <= tau1GateRange(2));
        maskTau2Range = (tau2GateRange(1) <= taus2Circularity) & (taus2Circularity <= tau2GateRange(2));
        maskDeltaDefoTau1Range = (deltaDefoRange(1) <= deltaDefoTau1) & (deltaDefoTau1 <= deltaDefoRange(2));
        maskDeltaDefoTau2Range = (deltaDefoRange(1) <= deltaDefoTau2) & (deltaDefoTau2 <= deltaDefoRange(2));

        strGate = '_gate';
    else
        maskCell = true(size(areaVec));

        maskTau1Range = true(size(taus1Circularity));
        maskTau2Range = true(size(taus1Circularity));
        maskDeltaDefoTau1Range = true(size(deltaDefoTau1));
        maskDeltaDefoTau2Range = true(size(deltaDefoTau2));

        strGate = '_noGate';
    end
    
   %% area
    areaVec(~maskCell) = NaN;
    
    %% velocity
    veloVec(~maskCell) = NaN;
    
    %% tau1
    tau1Vec = taus1Circularity;
    tau1Vec(~(maskCell & maskTau1Consistency & maskTau1Range)) = NaN;
    
    %% tau2
    tau2Vec = taus2Circularity;
    tau2Vec(~(maskCell & maskTau2Consistency & maskTau2Range)) = NaN;
    
    %% deltaDefoTau1
    deltaDefoTau1Vec = deltaDefoTau1;
    deltaDefoTau1Vec(~(maskCell & maskTau1Consistency & maskTau1Range & maskDeltaDefoTau1Range)) = NaN;
    
    %% deltaDefoTau2
    deltaDefoTau2Vec = deltaDefoTau2;
    deltaDefoTau2Vec(~(maskCell & maskTau2Consistency & maskTau2Range & maskDeltaDefoTau2Range)) = NaN;
    
    %% date & temp
%     idx = find(sampleName == '_');
%     date = sampleName(1:idx(1)-1);
%     if contains(sampleName,'Cold')
%         temp = 'Cold';
%     elseif contains(sampleName,'RT')
%         temp = 'RT';
%     elseif contains(sampleName,'Warm')
%         temp = 'Warm';
%     else
%         temp = 'undefined';
%         fprintf('Error: undefined temperature!\n');
%     end
    
    %% mask for non-empty rows
    maskValidRow = ~isnan(tau1Vec) | ~isnan(tau2Vec) | ~isnan(deltaDefoTau1Vec) | ~isnan(deltaDefoTau2Vec);
    
    %% table
    T = table;
%     T.date = repmat(date,length(cellNums),1);
%     T.sample = repmat(samples{idxSample},length(cellNums),1);
    T.measNum = measNums(maskValidRow)';
    T.cellNum = cellNums(maskValidRow)';
    T.area = areaVec(maskValidRow)';
    T.velocity = veloVec(maskValidRow)';
    T.tau1 = tau1Vec(maskValidRow)';
    T.tau2 = tau2Vec(maskValidRow)';
    T.deltaDefoTau1 = deltaDefoTau1Vec(maskValidRow)';
    T.deltaDefoTau2 = deltaDefoTau2Vec(maskValidRow)';
    
    writetable(T, [exportName '__' samples{idxSample} '.csv']);
%     if idxSample == 1
%         TComplete = T;
%     else
%         TComplete = vertcat(TComplete,T);
%     end
    
    fprintf('-');
end
fprintf('\n');

%% export
% writetable(TComplete, [exportName '.csv']);

diary off;
